<?php namespace App\Http\Services;

use App\AiConfig;
use App\AiRecord;
use App\AiScoreRule;
use App\Files;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Log;
use Requests;
use Requests_Exception;
use File;

class AiManager
{
    private $base_url = 'https://api.aikanshe.com';

    protected $jwtToken;
    protected $appId;
    protected $userKey;

    /**
     * @return mixed
     */
    public function getUserKey()
    {
        return $this->userKey;
    }

    /**
     * @param mixed $userKey
     */
    public function setUserKey($userKey): void
    {
        $this->userKey = $userKey;
    }

    /**
     * @return mixed
     */
    public function getJwtToken()
    {
        return $this->jwtToken;
    }

    /**
     * @param mixed $jwtToken
     */
    public function setJwtToken($jwtToken): void
    {
        $this->jwtToken = $jwtToken;
    }

    /**
     * @return mixed
     */
    public function getAppId()
    {
        return $this->appId;
    }

    /**
     * @param mixed $appId
     */
    public function setAppId($appId): void
    {
        $this->appId = $appId;
    }

    public function getNewUserKey(){
        $response = null;

        $url = '/account/login?tokenKey=get';
        try {
            $response = Requests::get($this->base_url . $url);
        } catch (Requests_Exception $ex) {
            \Log::error('Request Error To YunPian:'.$ex);
        }

        if (!$response->success) {
            return false;
        }

        if (empty($response->body))
            return false;

        return json_decode($response->body);
    }

    public static function loginAndGetJwtToken(){
        /** @var AiConfig $aiConfig */
        $aiConfig = AiConfig::where("id",">",0)->first();

        if(!$aiConfig)
            return false;

        $aiManager = new AiManager();

        if(!is_null($aiConfig->jwt_token) && $aiConfig->jwt_token != '' && $aiConfig->expire_timeout > time()){
            $aiManager->setJwtToken($aiConfig->jwt_token);
            return $aiConfig->jwt_token;
        }

        $result = $aiManager->getNewUserKey();

        if($result && isset($result->data) && isset($result->data->userKey)){
            $aiManager->setUserKey($result->data->userKey);
        }else{
            return false;
        }

        $response = null;
        $client = new Client();
        $param=[
            "appId"      => $aiConfig->username,
            "methodName" => "login",
            "password"   => $aiConfig->password,
            "timestamp"  => time(),
            "userKey"    => $aiManager->getUserKey()
        ];
        try {
            $response = $client->post($aiManager->base_url.'/account/login', ['headers'=>['Content-Type' =>'application/json'],'body' => \GuzzleHttp\json_encode($param),'options'=>['verify'=>false]]);
        } catch (GuzzleException $e) {
            Log::error('Request Error To YunPian:'.$e);
        }

        if ($response){
            if ($response->getStatusCode() == 200){
                $body = $response->getBody();
                if ($body){
                    try {
                        $data = \GuzzleHttp\json_decode($response->getBody());
                    }catch (\Exception $e){
                        Log::error("getShopInfoByLicense=>" . $e->getMessage());
                        return false;
                    }
                    if(isset($data->meta) && $data->meta->success == true){
                        $aiConfig->jwt_token      = $data->data->jwt;
                        $aiConfig->expire_timeout = time() + 3600;
                        $aiConfig->save();

                        $aiManager->setJwtToken($aiConfig->jwt_token);
                        return $aiConfig->jwt_token;
                    }
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    public static function aiDiagnose(Files $files){
        $filePath = $files->getLocalPath();

        /** @var AiConfig $aiConfig */
        $aiConfig = AiConfig::where("id",">",0)->first();

        if(!$aiConfig)
            return false;

        $aiManager = new AiManager();
        $url = '/pro/detect/v101';
        $headerParam = [
            "appId"         => $aiConfig->username,
            "authorization" => self::loginAndGetJwtToken()
        ];

        $params = [
            [
            'name'     => 'file',
            'contents' => fopen($filePath, 'r'),
            ]
        ];


        $response = null;
        $client = new Client();
        try {
            $response = $client->post($aiManager->base_url.$url, ['headers'=>$headerParam,'multipart'=>$params]);
        } catch (GuzzleException $e) {
            Log::error('Request Error To YunPian:'.$e);
        }

//        var_dump($response);die;
//        Log::error("responseresponseresponse=>".print_r($response,true));
        if ($response){
            if ($response->getStatusCode() == 200){
                $body = $response->getBody();
                if ($body){
                    try {
                        $data = \GuzzleHttp\json_decode($response->getBody());
                    }catch (\Exception $e){
                        Log::error("getShopInfoByLicense=>" . $e->getMessage());
                        return false;
                    }
                    return $data;
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    public static function getAiScore(AiRecord $aiRecord){
        $allScore = 0;

        $thatTaiseScore = AiScoreRule::whereName($aiRecord->taiseName)->first();
        if($thatTaiseScore){
            $allScore = $allScore + $thatTaiseScore->score;
        }

        $thatTaizhiScore = AiScoreRule::whereName($aiRecord->taizhiName)->first();
        if($thatTaizhiScore){
            $allScore = $allScore + $thatTaizhiScore->score;
        }

        $thatShemianScore = AiScoreRule::whereName($aiRecord->shemianName)->first();
        if($thatShemianScore){
            $allScore = $allScore + $thatShemianScore->score;
        }

        $thatShexinScore = AiScoreRule::whereName($aiRecord->shexinName)->first();
        if($thatShexinScore){
            $allScore = $allScore + $thatShexinScore->score;
        }

        return $allScore;
    }
}
